package wangjg.mda.gen.template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMark implements TemplateEngine {
	private String templCharset = "utf-8";
	private String genCharset = "utf-8";
	private String templateRoot;

	private Configuration getConfiguration(File dir){
		Configuration cfg = new Configuration();
		try {
			cfg.setDirectoryForTemplateLoading(dir);
		} catch (IOException e) {
			e.printStackTrace();
		}
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
		cfg.setDefaultEncoding(templCharset);
		return cfg;
	}
	
	private Template getTemplate(File file){
		try {
			Configuration cfg = this.getConfiguration(new File(getRootPath(file)));
			return cfg.getTemplate(file.getName(), templCharset);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void process(Map<String,Object> rootMap, File template, File out){
		OutputStream os = null;
		try{
			os = new FileOutputStream(out);
			Writer writer = new OutputStreamWriter(os, genCharset);
			this.process(rootMap, template, writer);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				if(os!=null)os.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	public void process(Map<String,Object> rootMap, File templFile, Writer out) throws Exception{
		Template t = this.getTemplate(templFile);
		t.process(rootMap, out);
	}

	@Override
	public String evaluate(Map<String, Object> rootMap, String template) {
		
		return null;
	}

	private String getTemplateName(File file){
		if(this.templateRoot==null){
			return file.getName();
		}else{
			int pos = this.templateRoot.length();
			String name = file.getPath();
			name = name.substring(pos);
			return name;
		}
	}
	
	private String getRootPath(File template){
		if(this.templateRoot!=null){
			return this.templateRoot;
		}else{
			return template.getParent();
		}
	}
	
	@Override
	public void setTemplateRoot(String templateRoot) {
		this.templateRoot = templateRoot;
	}

}
